package com.itheima.xunfeidemo;


import com.iflytek.cloud.ErrorCode;
import com.itheima.xunfeidemo.result.Result;
import com.itheima.xunfeidemo.result.xml.XmlResultParser;
import com.itheima.xunfeidemo.speech.setting.IseSettings;
import com.itheima.xunfeidemo.speech.util.FucUtil;
/*import com.iflytek.sunflower.FlowerCollector;*/
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * 语音评测demo
 */
public class IseDemo extends Activity implements OnClickListener {
    private static String TAG = IseDemo.class.getSimpleName();

    private final static String PREFER_NAME = "ise_settings";
    private final static int REQUEST_CODE_SETTINGS1= 1;
    private final static int REQUEST_CODE_SETTINGS2= 2;

    private EditText mEvaTextEditText;
    private EditText mResultEditText;
    private Button mIseStartButton;
    private Toast mToast;

    // 评测语种
    private String language;
    // 评测题型
    private String category;
    // 结果等级
    private String result_level;

    private String mLastResult;
    private SpeechEvaluator mIse;
    Intent intent;
    Intent intent1;
    String path;
    String path1;
    File myfile;
    String evaText;
    String ss;
    String name;
    // 评测监听接口
    private EvaluatorListener mEvaluatorListener = new EvaluatorListener() {

        @Override
        public void onResult(EvaluatorResult result, boolean isLast) {
            Log.d(TAG, "evaluator result :" + isLast);

            if (isLast) {
                StringBuilder builder = new StringBuilder();
                builder.append(result.getResultString());

                if(!TextUtils.isEmpty(builder)) {
                    mResultEditText.setText(builder.toString());
                }
                mIseStartButton.setEnabled(true);
                mLastResult = builder.toString();

                showTip("评测结束");
            }
        }

        @Override
        public void onError(SpeechError error) {
            mIseStartButton.setEnabled(true);
            if(error != null) {
                showTip("error:"+ error.getErrorCode() + "," + error.getErrorDescription());
                mResultEditText.setText("");
                mResultEditText.setHint("请点击“开始评测”按钮");
            } else {
                Log.d(TAG, "evaluator over");
            }
        }

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            Log.d(TAG, "evaluator begin");
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            Log.d(TAG, "evaluator stoped");
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            showTip("当前音量：" + volume);
            Log.d(TAG, "返回音频数据："+data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_lsedemo);
        mEvaTextEditText = (EditText) findViewById(R.id.ise_eva_text);
        mIse = SpeechEvaluator.createEvaluator(IseDemo.this, null);
        initUI();
        setEvaText("请上传文本(注意文本千万不要用手机wps打开，否则编码将不再是utf-8,无法正常实现功能)，在上传文本之后上传音频(选择的测试音频为output2)，开始测评，写入音频。");
    }


    private void initUI() {
        findViewById(R.id.audio1).setOnClickListener(IseDemo.this);
        findViewById(R.id.image_ise_set).setOnClickListener(IseDemo.this);
        findViewById(R.id.image_ise_set1).setOnClickListener(IseDemo.this);
        mEvaTextEditText = (EditText) findViewById(R.id.ise_eva_text);
        mResultEditText = (EditText)findViewById(R.id.ise_result_text);
        mIseStartButton = (Button) findViewById(R.id.ise_start);
        mIseStartButton.setOnClickListener(IseDemo.this);
        findViewById(R.id.ise_parse).setOnClickListener(IseDemo.this);
        findViewById(R.id.ise_stop).setOnClickListener(IseDemo.this);
        findViewById(R.id.ise_cancel).setOnClickListener(IseDemo.this);

        mToast = Toast.makeText(IseDemo.this, "", Toast.LENGTH_LONG);
    }

    @Override
    public void onClick(View view) {
        if( null == mIse ){
            // 创建单例失败，与 21001 错误为同样原因，参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            this.showTip( "创建对象失败，请确认 libmsc.so 放置正确，且有调用 createUtility 进行初始化" );
            return;
        }

        switch (view.getId()) {
            case R.id.image_ise_set:
                Intent intent = new Intent(IseDemo.this, textopen.class);
                startActivityForResult(intent, REQUEST_CODE_SETTINGS1);
                break;
            case R.id.audio1:
                executeStream();
                break;

            case R.id.ise_start:
                if (mIse == null) {
                    return;

                }

                evaText = mEvaTextEditText.getText().toString();
                mLastResult = null;
                mResultEditText.setText("");
                mResultEditText.setHint("请朗读以上内容");
                mIseStartButton.setEnabled(false);

                setParams();
                /*
                int ret = mIse.startEvaluating(evaText, null, mEvaluatorListener);
                //以下方法为通过直接写入音频的方式进行评测业务
				if (ret != ErrorCode.SUCCESS) {
					showTip("识别失败,错误码：" + ret);
				} else {
					showTip(getString(R.string.text_begin_ise));
					byte[] audioData = FucUtil.readAudioFile(IseDemo.this,"");
					if(audioData != null) {
						//防止写入音频过早导致失败
						try{
							new Thread().sleep(100);
						}catch (InterruptedException e) {
							Log.d(TAG,"InterruptedException :"+e);
						}
						mIse.writeAudio(audioData,0,audioData.length);
						mIse.stopEvaluating();
					}
				}*/


                break;
            case R.id.ise_parse:
                // 解析最终结果
                if (!TextUtils.isEmpty(mLastResult)) {
                    XmlResultParser resultParser = new XmlResultParser();
                    Result result = resultParser.parse(mLastResult);

                    if (null != result) {
                        mResultEditText.setText(result.toString());
                    } else {
                        showTip("解析结果为空");
                    }
                }
                break;
            case R.id.ise_stop:
                if (mIse.isEvaluating()) {
                    mResultEditText.setHint("评测已停止，等待结果中...");
                    mIse.stopEvaluating();
                }
                break;
            case R.id.ise_cancel: {
                mIse.cancel();
                mIseStartButton.setEnabled(true);
                mResultEditText.setText("");
                mResultEditText.setHint("请点击“开始评测”按钮");
                mLastResult = null;
                break;
            }
            case R.id.image_ise_set1:{
                Intent i = new Intent(IseDemo.this,audiopen.class);
                // 启动
                startActivityForResult(i, REQUEST_CODE_SETTINGS2);
                break;
        }
    }}

    private void executeStream() {
       /*intent1 = getIntent();
		path = (String) intent1.getSerializableExtra("path");
		File audio=new File(path);*/
        setParams();
        int ret = mIse.startEvaluating(evaText, null, mEvaluatorListener);
        //以下方法为通过直接写入音频的方式进行评测业务
        if (ret != ErrorCode.SUCCESS) {
            showTip("识别失败,错误码：" + ret);
        } else {
            showTip(getString(R.string.text_begin_ise));

            byte[] audioData = FucUtil.readAudioFile(IseDemo.this, name);
            if (audioData != null) {
                //防止写入音频过早导致失败
                try {
                    new Thread().sleep(100);
                } catch (InterruptedException e) {
                    Log.d(TAG, "InterruptedException :" + e);
                }
                mIse.writeAudio(audioData, 0, audioData.length);

            }

        }
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1){

            ss=data.getStringExtra("data");
            setEvaText(ss);
        }
        if(requestCode==2){

            name=data.getStringExtra("data");
            System.out.println("name:"+name);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != mIse) {
            mIse.destroy();
            mIse = null;
        }
    }

    // 设置评测试题
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void setEvaText(String tip) {
        String text = "";
        SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
        language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
        category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");


        if ("en_us".equals(language)) {
            if ("read_word".equals(category)) {
                text = getString(R.string.text_en_word);
            } else if ("read_sentence".equals(category)) {
                text = getString(R.string.text_en_sentence);
            }
        } else {
            // 中文评测
            if ("read_syllable".equals(category)) {
                text = getString(R.string.text_cn_syllable);
            } else if ("read_word".equals(category)) {
                text = getString(R.string.text_cn_word);
            } else if ("read_sentence".equals(category)) {
                //读取asset
                try {
                    /*intent = getIntent();
                    path = (String) intent.getSerializableExtra("path");
                    File myfile=new File(path);
                    FileInputStream fis = new FileInputStream(myfile);*/
                    InputStream fis = IseDemo.this.getAssets().open("lalaala.txt");
                    InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
                    BufferedReader bfr = new BufferedReader(isr);
                    String ln=bfr.readLine();
                    String input = getResources().getString(R.string.text_cn_sentence);
                    String output = String.format(tip, ln);
                    text = output;
                    isr.close();
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        mEvaTextEditText.setText(text);
        mResultEditText.setText("");
        mLastResult = null;
        mResultEditText.setHint("请点击“开始评测”按钮");
    }
   private void inputText(){
        try {
            intent = getIntent();
            path = (String) intent.getSerializableExtra("path");
            File myfile=new File(path);
            FileInputStream fis = new FileInputStream(myfile);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader bfr = new BufferedReader(isr);
            String ln;
            while ((ln = bfr.readLine()) != null) {
                mEvaTextEditText.setText(ln);
            }
            String input = getResources().getString(R.string.text_cn_sentence);
            String output = String.format(input, ln);

            isr.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void showTip(String str) {
        if(!TextUtils.isEmpty(str)) {
            mToast.setText(str);
            mToast.show();
        }
    }
    private void setParams() {
        SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
        // 设置评测语言
        language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置需要评测的类型
        category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");
        // 设置结果等级（中文仅支持complete）
        result_level = pref.getString(SpeechConstant.RESULT_LEVEL, "complete");
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        String vad_bos = pref.getString(SpeechConstant.VAD_BOS, "5000");
        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        String vad_eos = pref.getString(SpeechConstant.VAD_EOS, "1800");
        // 语音输入超时时间，即用户最多可以连续说多长时间；
        String speech_timeout = pref.getString(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");

        mIse.setParameter(SpeechConstant.LANGUAGE, language);
        mIse.setParameter(SpeechConstant.ISE_CATEGORY, category);
        mIse.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
        mIse.setParameter(SpeechConstant.VAD_BOS, vad_bos);
        mIse.setParameter(SpeechConstant.VAD_EOS, vad_eos);
        mIse.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, speech_timeout);
        mIse.setParameter(SpeechConstant.RESULT_LEVEL, result_level);
        mIse.setParameter(SpeechConstant.AUDIO_FORMAT_AUE,"opus");
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mIse.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
        intent1 = getIntent();
        path1 = (String) intent1.getSerializableExtra("path");
        mIse.setParameter(SpeechConstant.ISE_AUDIO_PATH, path1 + "/msc/ise.wav");

    }

    @Override
    protected void onResume() {
        // 开放统计 移动数据统计分析
		/*FlowerCollector.onResume(IseDemo.this);
		FlowerCollector.onPageStart(TAG);*/
        super.onResume();
    }

    @Override
    protected void onPause() {
/*		// 开放统计 移动数据统计分析
		FlowerCollector.onPageEnd(TAG);
		FlowerCollector.onPause(IseDemo.this);*/
        super.onPause();
    }
}
